#!/usr/bin/perl

use strict;
use warnings;

# Files
my $file_source = "perucontable-code-name.txt";
my $file_target = "perucontable-code-name.csv";

# Abrir archivo que contiene codigo nombre del plan de cuentas
open SOURCE, "<$file_source" or die "Imposible abrir el archivo $file_source";

# Arreglo de cuentas
my @accounts;
my $account;
my $line;

while (<SOURCE>) {

    # Leer primera linea
    $line = $_;
    chomp $line;

    # Borrar *
    $line =~ s/\*//g;

    # borrar espacios laterales
    $line = trim($line);

    # If is not only a line feed ...
    if (length($line)  > 0) {
	#print $line, "\n";
	# ... get the code and description account
	my @words = split(/\s/, $line);
	my $code = shift @words;
	my $name = join(" ", @words);
	# If the code have the form number dot number ...
	if ($code =~ /[0-9\.]/) {
	    # ... Add the account to the array
	    my %account;
	    $account{code} = $code;
	    $account{name} = $name;
	    $account{parent} = "";
	    push @accounts, \%account;
	    #print $account{code}, "|",  $account{name}, "\n";
	} else {
	    # ... otherwise, concatenate the line to
	    # previous description.
	    $account = $accounts[-1];
	    if ($account->{name} =~ /(.*)\-$/) {
		# delete hyphen
		#print "\tEureka : $account->{code} = $account->{name}\n";
		$account->{name} = $1;
	    }
	    else {
		$line = " " . $line;
	    }
	    $account->{name} = $account->{name} . $line;
	}
    }

}


# Close SOURCE
close SOURCE;

# Set up Parents
my $n_accounts = $#accounts + 1;
for (my $i = 0; $i < $n_accounts; $i++) {
    for (my $j = $i + 1; $j < $n_accounts; $j++) {
	if (index($accounts[$j]->{code}, $accounts[$i]->{code}) == 0) {
	    $accounts[$j]->{parent} = $accounts[$i]->{code};
	}
    }
}

# Open TARGET
open TARGET, ">$file_target" or die "Imposible abrir el archivo $file_target";

#Print the list of accounts
foreach $account (@accounts) {
    print TARGET $account->{code}, "|", $account->{name}, "|", $account->{parent}, "\n"; 
}

# Close TARGET
close TARGET;


# Tools
sub trim {
    my @out = @_ ? @_ : $_; 
    $_ = join(' ', split(' ')) for @out; 
    return wantarray ? @out : "@out"; 
}

sub add_to_file {
    my ($file, $line) = @_;
    open FILE, ">>$file" or die "Imposible abrir el archivo $file";
    print FILE $line, "\n";
    close FILE;
}
